package helpServlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.helpSession.HelpRequestsessionRemote;

/**
 * Servlet implementation class insertServlet
 */
public class insertHelpRequestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		drawPage(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		drawPage(request,response);
	}
	
	private void drawPage(HttpServletRequest request,
			HttpServletResponse response) {
		int idAb = Integer.parseInt((String)request.getParameter("idAbility"));
		String text = (String) request.getParameter("text");
		
		String d = (String) request.getParameter("date");
		Date utilDate = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
		try {
			utilDate = formatter.parse(d);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String hour = (String) request.getParameter("hour");
		
		int idSenderUser = (Integer)request.getSession().getAttribute("id");
		int idReceiverUser = Integer.parseInt((String)request.getParameter("idReceiverUser"));	
		try {
			Context jndiCtx = new InitialContext();
			HelpRequestsessionRemote hrs = (HelpRequestsessionRemote) jndiCtx
					.lookup("Progetto/HelpRequestsession/remote");
			if(hrs.insertHelpRequest(idSenderUser, idReceiverUser, idAb, utilDate, hour, text, -1)!=0)
				request.getSession().setAttribute("requestHelp", "requested");
			else
				request.getSession().setAttribute("requestHelp", "error");
			response.sendRedirect("/ProgettoWeb/ResearchedUser.html?id=" + idReceiverUser);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
